import configparser
import pymysql
from utils.PathUtils import PathUtils
import os

pathUtils = PathUtils()

db_config_path = os.path.join(pathUtils.get_root_dir(), 'config\db_config.ini')
# print(db_config_path)

class MySQLTool:
    def __init__(self):
        self.config_file = db_config_path
        self.connection = None

    def read_config(self):
        config = configparser.ConfigParser()
        config.read(self.config_file)
        return config['Database']

    def connect(self):
        db_config = self.read_config()
        self.connection = pymysql.connect(
            host=db_config['host'],
            port=int(db_config['port']),
            user=db_config['user'],
            password=db_config['password'],
            database=db_config['database'],
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )

    def disconnect(self):
        if self.connection:
            self.connection.close()

    def execute_query(self, query):
        with self.connection.cursor() as cursor:
            cursor.execute(query)
            result = cursor.fetchall()
            return result

    def execute_insert(self, query, values):
        with self.connection.cursor() as cursor:
            cursor.execute(query, values)
            self.connection.commit()


